package com.cn.zpark.controller;

import com.cn.zpark.pojo.User;
import com.cn.zpark.service.IUserService;
import com.cn.zpark.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @PackageName: com.cn.zpark.controller
 * @ClassName: RegUserServletController
 * @Description:
 * @author: RZS
 * @date: 2022/4/29  10:25
 */
@WebServlet("/reg_user.do")
public class RegUserServletController extends HttpServlet {

    // 声明service接口对象
    private IUserService userService = new UserServiceImpl();


    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取注册参数
        String username = request.getParameter("username");
        String uname = request.getParameter("uname");
        String password = request.getParameter("password");
        String email = request.getParameter("email");
        String phone = request.getParameter("phone");
        String sex = request.getParameter("sex");

        // 将注册参数封装到user对象中
        User user = new User();
        user.setUsername(username);
        user.setUname(uname);
        user.setPassword(password);
        user.setPhone(phone);
        user.setEmail(email);
        user.setSex(sex);
        user.setCreateUserTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        // 调用service执行注册功能
        boolean tag = userService.regUser(user);
        // 判断service执行结果，true表示注册成功，重定向到登录页面，否则注册失败，提示用户
        if(tag){
            // true表示注册成功，重定向到登录页面
            response.sendRedirect("login.jsp");
        }else {
            // 否则注册失败，提示用户
            request.setAttribute("message", "注册失败，请确认用户名是否被注册");
            // 转发给reg.jsp处理
            request.getRequestDispatcher("reg.jsp").forward(request, response);
        }
    }
}
